package com.example.demo.rx;

import com.example.demo.rx.cat.*;

import java.net.URL;
import java.util.Collections;
import java.util.List;

public class CatsHelper3Job2Func {
    ApiWrapper3Job apiWrapper;
    public AsyncJob<URL> saveTheCutest(String query) {
        AsyncJob<List<Cat>> catsListAsyncJob = apiWrapper.queryCats(query);
        AsyncJob<Cat> cutestCatAsyncJob = catsListAsyncJob.map(this::findCutest);
        AsyncJob<URL> storeURLAsyncJob = new AsyncJob<URL>() {
            @Override
            public void start(Callback<URL> callback) {
                cutestCatAsyncJob.start(new Callback<Cat>() {
                    @Override
                    public void onResult(Cat cutest) {
                        apiWrapper.store(cutest).start(new Callback<URL>() {
                            @Override
                            public void onResult(URL result) {
                                callback.onResult(result);
                            }

                            @Override
                            public void onError(Exception e) {
                                callback.onError(e);
                            }
                        });

                    }

                    @Override
                    public void onError(Exception e) {
                        callback.onError(e);
                    }
                });
            }
        };
        return storeURLAsyncJob;
    }

    private Cat findCutest(List<Cat> cats) {
        return Collections.max(cats);
    }
}
